<template>
	<div>
		<!-- vueCropper 剪裁图片实现-->
		<el-dialog
			title="图片剪裁"
			:visible.sync="dialogVisible"
			class="crop-dialog"
			append-to-body
			:close-on-click-modal="false"
			width="800px"
		>
			<div class="cropper-top">
				<div class="cropper_left">
					<div class="cropper-content">
						<div class="cropper" style="text-align:center">
							<VueCropper
								:style="{ width: '400px' }"
								ref="cropper"
								:img="option.img"
								:outputSize="option.size"
								:outputType="option.outputType"
								:info="true"
								:full="option.full"
								:canMove="option.canMove"
								:canMoveBox="canMoveBox"
								:original="option.original"
								:autoCrop="option.autoCrop"
								:fixed="fixed"
								:fixedNumber="fixedNumber"
								:centerBox="option.centerBox"
								:infoTrue="option.infoTrue"
								:fixedBox="fixedBox"
								:autoCropWidth="autoCropWidth"
								:autoCropHeight="autoCropHeight"
								@cropMoving="cropMoving"
								@realTime="realTime"
							/>
						</div>
					</div>
					<div class="action-box">
						<el-upload
							class="upload-demo"
							action=""
							:auto-upload="false"
							:show-file-list="false"
							:on-change="handleChangeUpload"
						>
							<el-button type="primary" size="mini">更换图片</el-button>
						</el-upload>
						<el-button type="primary" size="mini" @click="rotateLeftHandle">向左旋</el-button>
						<el-button type="primary" size="mini" @click="rotateRightHandle">向右旋</el-button>
						<el-button type="primary" size="mini" @click="changeScaleHandle(1)">放大</el-button>
						<el-button type="primary" size="mini" @click="changeScaleHandle(-1)">缩小</el-button>
					</div>
					<!-- <el-button type="primary" plain @click="clearImgHandle">清除图片</el-button> -->
					<!-- <el-button type="primary" plain @click="downloadHandle('blob')">下载</el-button> -->
				</div>
				<div class="cropper_right" v-if="round">
					<div class="preview_text">
						预览
					</div>
					<div :style="getStyle" class="previewImg">
						<div :style="previewFileStyle">
							<img :style="previews.img" :src="previews.url" alt="" />
						</div>
					</div>
				</div>
				<div class="cropper_right" v-else>
					<div class="preview_text">
						预览
					</div>
					<div :style="getStyle" class="previewImg">
						<div :style="previewFileStyle">
							<img :style="previews.img" :src="previews.url" alt="" />
						</div>
					</div>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="finish" :loading="loading">确认</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import request from "@/common/request"
export default {
	name: "v-cropper",
	props: {
		autoCropWidth: {
			type: Number,
			default: 200,
		},
		autoCropHeight: {
			type: Number,
			default: 200,
		},
		fixedBox: {
			type: Boolean,
			default: false,
		},
		fixed: {
			type: Boolean,
			default: true,
		},
		round: {
			type: Boolean,
			default: false,
		},
		previewWidth: {
			type: Number,
			default: 150,
		},
		fixedNumber: {
			type: Array,
			default: () => [1, 1],
		},
		outputType: {
			type: String,
			default: "png",
		},
		size: {
			type: Number,
			default: 3,
		},
		canMoveBox: {
			type: Boolean,
			default: true,
		},
		mode: {
			type: String,
			default: "contain",
		},
		maxImgSize: {
			type: Number,
			default: 2000,
		},
		enlarge: {
			type: Number,
			default: 1,
		},
	},
	data() {
		return {
			fileUploadUrl: window.$conf.commonConf.baseUrl + "/system/oss/upload", // 上传图片的地址
			isPreview: false,
			dialogVisible: false,
			previewImg: "", // 预览图片地址
			// 裁剪组件的基础配置option
			option: {
				img: "https://pic1.zhimg.com/80/v2-366c0aeae2b4050fa2fcbfc09c74aad4_720w.jpg", // 裁剪图片的地址
				info: true, // 裁剪框的大小信息
				outputSize: 1, // 裁剪生成图片的质量
				outputType: this.outputType, // 裁剪生成图片的格式
				canScale: true, // 图片是否允许滚轮缩放
				autoCrop: true, // 是否默认生成截图框
				canMoveBox: this.canMoveBox, // 截图框能否拖动
				canMove: true, // 上传图片是否可以移动
				autoCropWidth: this.autoCropWidth, // 默认生成截图框宽度
				autoCropHeight: this.autoCropHeight, // 默认生成截图框高度
				fixedBox: this.fixedBox, // 固定截图框大小 不允许改变
				fixed: this.fixed, // 是否开启截图框宽高固定比例
				fixedNumber: this.fixedNumber, // 截图框的宽高比例
				full: false, // 是否输出原图比例的截图,不失真
				original: false, // 上传图片按照原始比例渲染
				centerBox: true, // 截图框是否被限制在图片里面
				infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
				mode: this.mode, // 图片默认渲染方式
				maxImgSize: this.maxImgSize, // 上传图片最大宽度和高度
				enlarge: this.enlarge, // 图片根据截图框输出比例倍数
			},
			// 防止重复提交
			loading: false,
			fileinfo: {},
			previews: {},
			previewFileStyle: {},
			getStyle: { width: "", height: "" },
			tempScale: 0,
		}
	},
	methods: {
		// 上传按钮 限制图片大小和类型
		handleChangeUpload(file) {
			this.fileinfo = file // 保存下当前文件的一些基本信息
			const isJPG = file.raw.type === "image/jpeg" || file.raw.type === "image/png"
			const isLtnM = file.size / 1024 / 1024 < this.size
			if (!isJPG) {
				this.$message.error("上传头像图片只能是 JPG/PNG 格式!")
				return false
			}
			if (!isLtnM) {
				this.$message.error(`上传头像图片大小不能超过 ${this.size}MB!`)
				return false
			}
			// 上传成功后将图片地址赋值给裁剪框显示图片
			this.$nextTick(async () => {
				// base64方式
				// this.option.img = await fileByBase64(file.raw)
				this.option.img = URL.createObjectURL(file.raw)
				this.dialogVisible = true
				this.loading = false
			})
		},
		// 放大/缩小
		changeScaleHandle(num) {
			num = num || 1
			this.$refs.cropper.changeScale(num)
		},
		// 左旋转
		rotateLeftHandle() {
			this.$refs.cropper.rotateLeft()
		},
		// 右旋转
		rotateRightHandle() {
			this.$refs.cropper.rotateRight()
		},
		// 下载
		downloadHandle(type) {
			let aLink = document.createElement("a")
			aLink.download = "author-img"
			if (type === "blob") {
				this.$refs.cropper.getCropBlob(data => {
					// let downImg = window.URL.createObjectURL(data)
					aLink.href = window.URL.createObjectURL(data)
					aLink.click()
				})
			} else {
				this.$refs.cropper.getCropData(data => {
					// let downImg = data
					aLink.href = data
					aLink.click()
				})
			}
		},
		// 清理图片
		clearImgHandle() {
			this.option.img = ""
		},
		// 截图框移动回调函数
		cropMoving() {
			// 截图框的左上角 x，y和右下角坐标x，y
			// let cropAxis = [data.axis.x1, data.axis.y1, data.axis.x2, data.axis.y2]
			// console.log(cropAxis)
		},
		realTime(data) {
			this.previews = data // 预览img图片
			this.tempScale = this.previewWidth / data.w
			this.previewFileStyle = {
				width: data.w + "px",
				height: data.h + "px",
				margin: 0,
				overflow: "hidden",
				zoom: this.tempScale,
				position: "relative",
				border: "1px solid #e8e8e8",
				"border-radius": this.round ? "50%" : "10px",
			}
		},
		finish() {
			// 获取截图的 blob 数据
			this.$refs.cropper.getCropBlob(async blob => {
				this.loading = true
				this.previewImg = URL.createObjectURL(blob)
				this.isPreview = true

				// 注此时的data是一个Blob数据，部分接口接收的是File转化的FormData数据
				let formData = new FormData()
				formData.append(
					"upfile",
					new File(
						[blob], // 将Blob类型转化成File类型
						this.fileinfo.name, // 设置File类型的文件名称
						{ type: this.fileinfo.type }, // 设置File类型的文件类型
					),
				)
				formData.append("width", this.autoCropWidth)
				formData.append("height", this.autoCropHeight)
				try {
					const data = await request("post", this.fileUploadUrl, formData)
					this.$emit("success", data)
					this.dialogVisible = false
					this.loading = false
				} catch (error) {
					this.loading = false
					console.log(error)
				}
			})
			// 获取截图的 base64 数据

			// this.$refs.cropper.getCropData(data => {
			// 	console.log(data, "base64")
			// })
		},
	},
	watch: {
		// previewWidth: {
		// 	handler(val) {
		// 		// 对对象进行深度监听
		// 		this.getStyle = {
		// 			width: val + "px", // 预览宽度
		// 			height: val / this.option.fixedNumber[0] + "px", // 预览高度
		// 		}
		// 	},
		// 	deep: true,
		// },
	},
}
</script>

<style lang="scss" scoped>
.cropper-content {
	.cropper {
		width: auto;
		height: 350px;
		// ::v-deep .cropper-view-box {
		// 	border-radius: 50%;
		// }
	}
}
.action-box {
	margin-top: 5px;
	width: 100%;
	.upload-demo {
		margin-right: auto;
	}
	// margin-top: 30px;
	display: flex;
	justify-content: flex-end;
}
.dialog-footer {
	display: flex;
	justify-content: flex-end;
}
.cropper-top {
	overflow: hidden;
	display: flex;
	justify-content: center;
	.cropper_left {
		width: calc(100% - 150px);
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.cropper_right {
		width: 200px;
		flex: 1;
		margin-left: 44px;
		.preview_text {
			margin-bottom: 12px;
		}
	}
}
.previewImg {
}
</style>
